package com.wl.srb.sms.controller.api;


import com.wl.common.exception.Assert;
import com.wl.common.result.R;
import com.wl.common.result.ResponseEnum;
import com.wl.common.util.RandomUtils;
import com.wl.common.util.RegexValidateUtils;
import com.wl.srb.sms.service.SmsService;
import com.wl.srb.sms.util.SmsProperties;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/sms")
@Api(tags = "短信管理")
@CrossOrigin //跨域
@Slf4j
public class ApiSmsController {
    @Autowired
    SmsService smsService;
    @Autowired
    RedisTemplate redisTemplate;
    @GetMapping("/send/{mobile}")
    public R send(@PathVariable("mobile") String mobile){
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile),ResponseEnum.MOBILE_ERROR);
        String fourBitRandom = RandomUtils.getFourBitRandom();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", fourBitRandom);
        smsService.send(mobile, SmsProperties.TEMPLATE_CODE,map);
        redisTemplate.opsForValue().set("srb:sms:code:"+mobile,fourBitRandom,5, TimeUnit.MINUTES);
        return R.ok().message("短信发送成功");
    }
}
